package org.example.se.io.randomAccessFile;

import org.example.se.io.FileInputStreamTest;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLDecoder;

/**
 * RandomAccessFile-随机访问文件线程，用于多线程写文件
 */
public class AccessFileThread {

    /**
     * destFile：待写入的目标文件
     * seek：文件指针定位到指定的位置
     * content：待写入的内容
     */
    private File destFile;
    private int seek;
    private byte[] content;

    public AccessFileThread(File destFile, int seek, byte[] content) {
        this.destFile = destFile;
        this.seek = seek;
        this.content = content;
    }

    public void run() throws IOException {
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(destFile, "rw");
            randomAccessFile.seek(seek);
            randomAccessFile.write(content);
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String srcClassPath = "data/images/超清美女.jpg";
        String path = FileInputStreamTest.class.getClassLoader().getResource(srcClassPath).getPath();
        path = URLDecoder.decode(path, "utf-8");

        File sourceFile = new File(path);
        File destFile = new File(FileSystemView.getFileSystemView().getHomeDirectory(), srcClassPath);

        int threadCount = 3;

        long length = sourceFile.length();
        System.out.println(length);

        RandomAccessFile raf = new RandomAccessFile(destFile, "rw");
        //预分配 1M 的文件空间
        raf.setLength(length);
        raf.close();

        long l = length / 3;


        // 预分配文件所占的磁盘空间，磁盘中会创建一个指定大小的文件


        // 所要写入的文件内容
        String s1 = "第一个字符串";
        String s2 = "第二个字符串";
        String s3 = "第三个字符串";
        String s4 = "第四个字符串";
        String s5 = "第五个字符串";

        // 利用多线程同时写入一个文件
//        new AccessFileThread(1024 * 1, s1.getBytes("utf-8")).start(); // 从文件的1024字节之后开始写入数据
    }


}
